use std::{io::Write, path::PathBuf, process::Command};

fn main() {
    println!("cargo::rustc-check-cfg=cfg(hard_float)");

    let target = std::env::var("TARGET").unwrap();


    if target.as_str() == "aarch64-unknown-none" {
        println!("cargo::rustc-cfg=hard_float");
    }

    println!("cargo:rerun-if-changed=pie_boot.ld");
    println!("cargo:rustc-link-search={}", out_dir().display());

    let content = include_str!("pie_boot.ld");
    let mut file =
        std::fs::File::create(out_dir().join("pie_boot.x")).expect("pie_boot.x create failed");
    file.write_all(content.as_bytes())
        .expect("pie_boot.x write failed");

    let loader_path =
        std::env::var_os("CARGO_BIN_FILE_PIE_BOOT_ARM_LOADER").expect("loader binary");

    println!("loader path: {}", loader_path.display());

    let loader_dst = out_dir().join("loader.bin");

    let status = Command::new("rust-objcopy")
        .args(["--strip-all", "-O", "binary"])
        .arg(&loader_path)
        .arg(loader_dst)
        .status()
        .expect("objcopy failed");

    assert!(status.success());

    println!("target dir: {}", target_dir().display());

    let _ = std::fs::remove_file(target_dir().join("loader.elf"));
    std::fs::copy(&loader_path, target_dir().join("loader.elf")).unwrap();
}

fn out_dir() -> PathBuf {
    PathBuf::from(std::env::var("OUT_DIR").unwrap())
}

fn target_dir() -> PathBuf {
    PathBuf::from(std::env::var("OUT_DIR").unwrap())
        .ancestors()
        .nth(3)
        .unwrap()
        .into()
}
